package com.dhl.fin.api.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import com.dhl.fin.api.common.util.StringUtil;
import com.dhl.fin.api.dto.CronJobFunctionParamDTO;

import java.util.Date;
import java.util.function.Consumer;

/**
 * @author CuiJianbo
 * @since 2025/5/4
 */
public class CronJobUtil {

    /**
     * 注册定时任务
     */
    public static String registerCronJob(String cronJob, CronJobFunctionParamDTO paramDTO, Consumer<CronJobFunctionParamDTO> taskFunction) {
        if (StringUtil.isEmpty(cronJob)) {
            throw new RuntimeException("cronJob is empty");
        }
        if (paramDTO == null) {
            throw new RuntimeException("paramDTO is null");
        }
        return CronUtil.schedule(cronJob, (Task) () -> taskFunction.accept(paramDTO));
    }

    /**
     * 注销定时任务
     */
    public static void disableCronJob(String scheduleId) {
        if (StringUtil.isNotEmpty(scheduleId)) {
            CronUtil.remove(scheduleId);
        }
    }

    /**
     * 日期转cron表达式
     */
    public static String dateToCron(Date remindDate) {
        int month = DateUtil.month(remindDate) + 1;
        int days = DateUtil.dayOfMonth(remindDate);
        int minute = DateUtil.minute(remindDate);
        int hour = DateUtil.hour(remindDate, true);
        return String.format("0 %d %d %d %d ?", minute, hour, days, month);

    }
}
